// ==========================================================================
// gin-sns自动生成业务逻辑层相关代码，只生成一次，按需修改,再次生成不会覆盖.
// date：2021-02-21 13:45:53 +0800 CST
// path: app/service/module/collectarticle_service.go
// author：jon
// ==========================================================================
package module

import (
	"errors"
	"gin-sns/app/common/baiduai"
	"gin-sns/app/dao/module/collectarticle"
	"gin-sns/app/model"
	"gin-sns/app/model/constants"
	collectarticleModel "gin-sns/app/model/module/collectarticle"
	"strings"
	"time"

	"github.com/gin-gonic/gin"

	"gin-sns/app/ginframe/tools"
	"gin-sns/app/ginframe/utils/convert"
	"gin-sns/app/ginframe/utils/page"
)

var CollectarticleService = newCollectarticleService()

func newCollectarticleService() *collectarticleService {
	return &collectarticleService{}
}

type collectarticleService struct {
}

//根据主键查询数据
func (s *collectarticleService) SelectRecordById(id int64) (*collectarticleModel.Entity, error) {
	return collectarticle.CollectarticleDao.SelectById(id)
}

//
func (s *collectarticleService) SelectRecordsIn(idarr []int64) ([]collectarticleModel.Entity, error) {

	list, err := collectarticle.CollectarticleDao.FindIn("id", idarr)
	if list != nil && len(list) > 0 {
		err = errors.New("not found")
		list = nil
	}
	return list, err
}

//根据主键删除数据
func (s *collectarticleService) DeleteRecordById(id int64) bool {
	return collectarticle.CollectarticleDao.DeleteById(id)
}

//批量删除数据记录
func (s *collectarticleService) DeleteRecordByIds(ids string) int64 {
	ida := convert.ToInt64Array(ids, ",")
	result, err := collectarticle.CollectarticleDao.DeleteBatch(ida...)
	if err != nil {
		return 0
	}
	return result
}

//添加数据
func (s *collectarticleService) AddSave(req *collectarticleModel.AddReq, ctx *gin.Context) (int64, error) {
	var entity collectarticleModel.Entity

	//entity.Id = req.Id
	entity.UserId = req.UserId
	entity.RuleId = req.RuleId
	entity.LinkId = req.LinkId
	entity.Title = req.Title
	entity.Summary = req.Summary
	entity.Content = req.Content
	entity.ContentType = req.ContentType
	entity.SourceUrl = req.SourceUrl
	entity.SourceId = req.SourceId
	entity.SourceUrlMd5 = req.SourceUrlMd5
	entity.SourceTitleMd5 = req.SourceTitleMd5
	entity.ArticleId = req.ArticleId
	entity.Status = req.Status
	entity.CreateTime = time.Now()
	//entity.CreateBy = ""

	//user := system.UserService.GetProfile(ctx)

	//if user != nil {
	//	entity.CreateBy = user.LoginName
	//}

	_, err := collectarticle.CollectarticleDao.Insert(&entity)
	return entity.Id, err
}

//修改数据
func (s *collectarticleService) EditSave(req *collectarticleModel.EditReq, ctx *gin.Context) (int64, error) {
	entity := &collectarticleModel.Entity{Id: req.Id}
	ok, err := collectarticle.CollectarticleDao.FindOne(entity)

	if err != nil {
		return 0, err
	}

	if !ok {
		return 0, errors.New("数据不存在")
	}

	entity.UserId = req.UserId
	entity.RuleId = req.RuleId
	entity.LinkId = req.LinkId
	entity.Title = req.Title
	entity.Summary = req.Summary
	entity.Content = req.Content
	entity.ContentType = req.ContentType
	entity.SourceUrl = req.SourceUrl
	entity.SourceId = req.SourceId
	entity.SourceUrlMd5 = req.SourceUrlMd5
	entity.SourceTitleMd5 = req.SourceTitleMd5
	entity.ArticleId = req.ArticleId
	entity.Status = req.Status
	//entity.UpdateTime = time.Now()
	//entity.UpdateBy = ""

	//user := system.UserService.GetProfile(ctx)

	//if user == nil {
	//	entity.UpdateBy = user.LoginName
	//}

	return collectarticle.CollectarticleDao.Update(entity)
}

//根据条件查询数据
func (s *collectarticleService) SelectListAll(params *collectarticleModel.SelectPageReq) ([]collectarticleModel.Entity, error) {
	return collectarticle.CollectarticleDao.SelectListAll(params)
}

//根据条件分页查询数据
func (s *collectarticleService) SelectListByPage(params *collectarticleModel.SelectPageReq) ([]collectarticleModel.Entity, *page.Paging, error) {
	return collectarticle.CollectarticleDao.SelectListByPage(params)
}

// 导出excel
func (s *collectarticleService) Export(param *collectarticleModel.SelectPageReq) (string, error) {
	head := []string{"", "用户id", "规则id", "链接id", "名称", "总揽", "内容", "内容类型", "源地址", "源id", "源地址MD5", "源名称MD5", "文章id", "0未审核 1正常状态 2审核未通过 3删除", "创建时间"}
	col := []string{"id", "user_id", "rule_id", "link_id", "title", "summary", "content", "content_type", "source_url", "source_id", "source_url_md5", "source_title_md5", "article_id", "status", "create_time"}
	return collectarticle.CollectarticleDao.SelectListExport(param, head, col)
}

// 文章是否存在
func (s *collectarticleService) IsExists(sourceUrl, title string) bool {

	var entity collectarticleModel.Entity
	entity.SourceUrl = sourceUrl
	entity.SourceUrlMd5 = tools.MD5(sourceUrl)
	ok, _ := collectarticle.CollectarticleDao.FindOne(&entity)
	if ok {
		return true
	}

	var entity2 collectarticleModel.Entity
	entity2.Title = title
	entity2.SourceTitleMd5 = tools.MD5(title)
	ok2, _ := collectarticle.CollectarticleDao.FindOne(&entity2)
	if ok2 {
		return true
	}

	return false
}

// 创建采集文章
func (s *collectarticleService) Create(ruleId, userId int64, sourceUrl, title, summary, content string) (*collectarticleModel.Entity, error) {
	title = strings.TrimSpace(title)
	summary = strings.TrimSpace(summary)
	content = strings.TrimSpace(content)

	if len(title) == 0 || len(content) == 0 {
		return nil, errors.New("文章标题或内容为空")
	}

	entity := &collectarticleModel.Entity{
		UserId:         userId,
		RuleId:         ruleId,
		Title:          title,
		Summary:        summary,
		Content:        content,
		Status:         model.CollectArticleStatusPending,
		ContentType:    constants.ContentTypeHtml,
		SourceUrl:      sourceUrl,
		SourceUrlMd5:   tools.MD5(sourceUrl),
		SourceTitleMd5: tools.MD5(title),
		CreateTime:     time.Now(),
	}

	_, err := collectarticle.CollectarticleDao.Insert(entity)
	if err != nil {
		return nil, err
	}
	return entity, err
}

// 发布采集文章
func (s *collectarticleService) Publish(collectArticleId int64) error {

	ca, _ := s.SelectRecordById(collectArticleId)
	if ca == nil {
		return errors.New("没找到该采集文章")
	}

	var analyzeRet *baiduai.AiAnalyzeRet
	if ca.ContentType == constants.ContentTypeHtml {
		analyzeRet, _ = baiduai.GetAi().AnalyzeHtml(ca.Title, ca.Content)
	} else if ca.ContentType == constants.ContentTypeMarkdown {
		analyzeRet, _ = baiduai.GetAi().AnalyzeMarkdown(ca.Title, ca.Content)
	}

	var tags []string
	var summary string
	if analyzeRet != nil {
		tags = analyzeRet.Tags
		summary = analyzeRet.Summary
	}

	article, err := ArticleService.Publish(ca.UserId, ca.Title, summary, ca.Content, ca.ContentType,
		0, tags, ca.SourceUrl, false)
	if err != nil {
		return err
	}

	ca.Status = model.CollectArticleStatusPublished
	ca.ArticleId = article.Id
	_, err = collectarticle.CollectarticleDao.Update(ca)

	return err
}

/*
type CollectArticleScanCallback func(*collectarticleModel.Entity)

// 扫描
func Scan(callback CollectArticleScanCallback) {
	var cursor int64
	for {
		list := collectarticleModel.Find( tools.NewSqlCnd().Where("id > ?", cursor).Asc("id").Limit(100))
		if len(list) == 0 {
			break
		}
		for _, item := range list {
			cursor = item.Id
			callback(&item)
		}
	}
}
*/
